Skip to content

Caution that c++ compiler can implicitly convert some class objects without you expliciting#13

Open
Butcher3Years wants to merge 1 commit intoNew--keywordfrom
Implicit-conversion----Explicit-Keyword
Open

Caution that c++ compiler can implicitly convert some class objects without you expliciting#13
Butcher3Years wants to merge 1 commit intoNew--keywordfrom
Implicit-conversion----Explicit-Keyword

Conversation

@Butcher3Years
Copy link
Copy Markdown
Owner

Implicit Conversion vs explicit Keyword in C++

In C++, single-argument constructors can allow implicit conversion from other types to your class — unless you mark them explicit.

The Problem (Implicit Conversion)

class Entity {
private:
    std::string m_Name;
    int m_Age;

public:
    Entity(const std::string& name)           // ← single-argument ctor
        : m_Name(name), m_Age(-1) {}

    Entity(int age)                           // ← another single-argument ctor
        : m_Name("Unknown"), m_Age(age) {}
};

int main() {
    Entity a = "Cherno";     // compiles!
    Entity b = 22;           // also compiles!
}

The Fix: explicit Keyword

class Entity {
    // ...
public:
    explicit Entity(const std::string& name)
        : m_Name(name), m_Age(-1) {}

    explicit Entity(int age)
        : m_Name("Unknown"), m_Age(age) {}
};

Now what happens?

Entity a = "Cherno";     // COMPILE ERROR (good!)
Entity b = 22;           // COMPILE ERROR (good!)

Entity a("Cherno");                  // direct initialization → OK
Entity a = Entity("Cherno");         // explicit construction → OK
Entity b(22);                        // direct initialization → OK

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant